function flattenLocationTree(tree) {
  const treeArr = [tree];
  const res = [];
  for (let item of treeArr) {
    function dfs(node, parentId) {
      res.push({ id: node.id, name: node.name, parentId });
      const children = node.children
      if (children.length > 0) {
        for (let child of children) {
          dfs(child, node.id);
        }
      }
    }
    dfs(item, null);
  }
  return res;
}
// 示例树状结构
const tree = {
  id: 1,
  name: '中国',
  children: [
    {
      id: 2,
      name: '北京市',
      children: [
        {
          id: 3,
          name: '东城区',
          children: [],
        },
        {
          id: 4,
          name: '西城区',
          children: [],
        },
      ],
    },
    {
      id: 5,
      name: '上海市',
      children: [
        {
          id: 6,
          name: '黄浦区',
          children: [],
        },
        {
          id: 7,
          name: '徐汇区',
          children: [],
        },
      ],
    },
  ],
};

// 调用函数将树状结构打平
const flattenedLocations = flattenLocationTree(tree);

// 打印结果
console.log(flattenedLocations);
// [
//   { id: 1, name: '中国', parentId: null },
//   { id: 2, name: '北京市', parentId: 1 },
//   { id: 3, name: '东城区', parentId: 2 },
//   { id: 4, name: '西城区', parentId: 2 },
//   { id: 5, name: '上海市', parentId: 1 },
//   { id: 6, name: '黄浦区', parentId: 5 },
//   { id: 7, name: '徐汇区', parentId: 5 }
// ]
